package com.jh.concurrent.principle;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title ConcurrentDemo.java
 * @package com.jh.concurrent.principle
 * @description 多线程原子性demo
 * @date 2019-05-13 09:17
 */
public class ConcurrentDemo {

    private static int count = 0;

    /**
     * 如果将 synchronized 放置到static前面，就是修饰静态方法，相当于作用域是类对象
     */
    private static void inc() {
        /**
         * 同步代码块的修饰对象是类对象时，和将关键字放置到方法前是一样的
         */
        synchronized (ConcurrentDemo.class) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> ConcurrentDemo.inc()).start();
        }

        Thread.sleep(3000);
        System.out.println("运行结果：" + count);
    }
}
